package com.polaris.live.ui.recharge

import android.graphics.Color
import android.os.Bundle
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.StringUtils
import com.lxj.xpopup.XPopup
import com.polaris.live.R.color
import com.polaris.live.adapter.recharge.BuyGameBeansAdapter
import com.polaris.live.adapter.recharge.RechargeBannerAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.dp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.AppCodeUtils.arTo
import com.polaris.live.databinding.FragmentGameBeansBinding
import com.polaris.live.dialog.GameBenasWhatDialog
import com.polaris.live.dialog.GameCustomizeDialog
import com.polaris.live.im.manager.ImNoticeManager
import com.polaris.live.translation.R
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.route.RouterUtils
import com.polaris.live.utils.route.SpanClickUtils
import com.polaris.live.viewmodel.RechargeViewModel
import com.zhpan.indicator.enums.IndicatorSlideMode

/**
 * GameBeansFragment
 *
 * @author Created by 半仙 on 2024/3/13/013 14:46
 */
class GameBeansFragment : BaseVbFragment<RechargeViewModel, FragmentGameBeansBinding>() {

    private val mAdapter by lazy { BuyGameBeansAdapter() }

    private val mBannerAdapter: RechargeBannerAdapter by lazy {
        RechargeBannerAdapter()
    }

    override fun initView(savedInstanceState: Bundle?) {
        init()
        mViewModel.getGameCoin()
        initListener()
        initObserver()

        mBinding.bannerView.apply {
            registerLifecycleObserver(lifecycle)
            setAdapter(mBannerAdapter)
            setIndicatorSlideMode(IndicatorSlideMode.NORMAL)
            setIndicatorVisibility(View.GONE)
            setRoundCorner(10.dp)
            setScrollDuration(500)
        }

        mViewModel.getBannerList()

        mBinding.tvGameBeanRule.text =
            "1 ${StringUtils.getString(R.string.diamond_string)} = 1 ${StringUtils.getString(R.string.game_beans_string)}".arTo()
    }

    private fun initObserver() {
        setGameCoin()

        mViewModel.gameCoinLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mAdapter.setList(it.prices)
            })
        }

        ImNoticeManager.observeGameAccountChange(this) {
            setGameCoin()
        }

        mViewModel.bannerLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.isEmpty()) {
                    mBinding.consLayout.visibility = View.GONE
                } else {
                    mBinding.consLayout.visibility = View.VISIBLE
                }
                mBinding.bannerView.create(it)
            })
        }
    }

    private fun initListener() {
        mBinding.gameWhat.setOnSingleClickListener {
            XPopup.Builder(requireContext())
                .hasShadowBg(true)
                .isDestroyOnDismiss(true)
                .asCustom(GameBenasWhatDialog(requireContext()))
                .show()
        }
        mBinding.tvCustomRedemption.setOnSingleClickListener {
            XPopup.Builder(requireContext())
                .hasShadowBg(true)
                .isDestroyOnDismiss(true)
                .asCustom(GameCustomizeDialog(requireContext(), mViewModel))
                .show()
        }
        mAdapter.setOnItemChildClickListener { _, view, position ->
            val item = mAdapter.getItemOrNull(position) ?: return@setOnItemChildClickListener
            when (view.id) {
                com.polaris.live.R.id.ll_game_coin_back -> {
                    mViewModel.gameCoinExchange(item, requireContext())
                }
            }
        }
        mBinding.tvEmail.setOnSingleClickListener {
            RouterUtils.routerWeb(
                ImageUtils.imgPath(AppConst.Customer.suffix),
                mapOf("type" to "${CommonConst.FAQType.RECHARGE}")
            )
        }
    }

    private fun setGameCoin() {
        mBinding.userCoin.text =
            "${UserManager.getUser().account?.userGameCoins?.toString() ?: 0}" + " "
    }

    private fun init() {
        mBinding.gameRecycler.apply {
            adapter = mAdapter
            layoutManager = LinearLayoutManager(context)
            itemAnimator = null
        }


        mBinding.tvEmail.text = SpanUtils.with(mBinding.tvEmail)
            .append(StringUtils.getString(R.string.exchange_encountering))
            .setUnderline()
            .create()

        val span = SpanClickUtils.with(mBinding.rechargeBottomText)
            .append("${resources.getText(R.string.recharge_terms_of_service)}").setUnderline()
            .setClickSpan(object : ClickableSpan() {
                override fun updateDrawState(paint: TextPaint) {
                    paint.isUnderlineText = true
                    paint.bgColor = Color.TRANSPARENT
                }

                override fun onClick(widget: View) {
                    RouterUtils.routerGoto(CommonConst.Agreement.TERMS_OF_SERVICE)
                }
            })
            .setForegroundColor(Color.parseColor("#FFFFFF"))
            .append(" ${resources.getText(R.string.and)} ")
            .setForegroundColor(ColorUtils.getColor(color.fff_70))
            .append("${resources.getText(R.string.recharge_privacy_policy)}").setUnderline()
            .setClickSpan(object : ClickableSpan() {
                override fun updateDrawState(paint: TextPaint) {
                    paint.isUnderlineText = true
                    paint.bgColor = Color.TRANSPARENT
                }

                override fun onClick(widget: View) {
                    RouterUtils.routerGoto(CommonConst.Agreement.PRIVACY_POLICY)
                }
            })
            .setForegroundColor(ColorUtils.getColor(color.white))
            .create()

        mBinding.rechargeBottomText.text = span
    }
}